﻿using ImperialServer.Common.Entities;
using ImperialUtilities.Exceptions;
using ImperialUtilities.Utilities;
using ImperialWebSite.Content.Resources;
using ImperialWebSite.Controllers;
using ImperialWebSite.Presenters.Citizen.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace ImperialWebSite.Presenters.Citizen.Classes
{
    public class QueryCitizensPresenter
    {
        private IQueryCitizens _view;
        private CitizenController _controller;
        private EventViewer _logger;

        public QueryCitizensPresenter(IQueryCitizens view)
        {
            _view = view;
            _controller = new CitizenController();
            _logger = new EventViewer("ImperialWebSite.Presenters.Citizen.Classes");
        }

        /// <summary>
        /// Metodo que hace la carga del drop down list de roles
        /// </summary>
        internal void LoadRolesDropdownLists()
        {
            DataTable dt = null;
            try
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.enterMessageInfo, "LoadRolesDropdownLists"));
                dt = _controller.SelectAllRoles();
                _view.RolesDataSource = dt;
                _view.RolesDataTextField = dt.Columns["roleName"].ToString();
                _view.RolesDataValueField = dt.Columns["idRole"].ToString();
                HttpContext.Current.Trace.Write(Messages.successfulTransactionMessage);
            }
            catch (ImperialException ie)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = ie.ImperialMessage;
            }
            catch (Exception e)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = Messages.failureTransactionMessage;
                _logger.WriteEventViewerLog("LoadRolesDropdownLists", e.Message, true);
            }
            finally
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.exitMessageInfo, "LoadRolesDropdownLists"));
            }
        }

        /// <summary>
        /// Metodo que hace la carga del drop down list de especies
        /// </summary>
        internal void LoadSpeciesDropdownLists()
        {
            DataTable dt = null;
            try
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.enterMessageInfo, "LoadSpeciesDropdownLists"));
                dt = _controller.SelectAllSpecies();
                _view.SpeciesDataSource = dt;
                _view.SpeciesDataTextField = dt.Columns["specieName"].ToString();
                _view.SpeciesDataValueField = dt.Columns["idSpecie"].ToString();
                HttpContext.Current.Trace.Write(Messages.successfulTransactionMessage);
            }
            catch (ImperialException ie)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = ie.ImperialMessage;
            }
            catch (Exception e)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = Messages.failureTransactionMessage;
                _logger.WriteEventViewerLog("LoadSpeciesDropdownLists", e.Message, true);
            }
            finally
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.exitMessageInfo, "LoadSpeciesDropdownLists"));
            }
        }

        /// <summary>
        /// Metodo que hace la carga del drop down list de estatus
        /// </summary>
        internal void LoadStatusesDropdownLists()
        {
            DataTable dt = null;
            try
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.enterMessageInfo, "LoadStatusesDropdownLists"));
                dt = _controller.SelectAllStatuses();
                _view.StatusesDataSource = dt;
                _view.StatusesDataTextField = dt.Columns["statusName"].ToString();
                _view.StatusesDataValueField = dt.Columns["idStatus"].ToString();
                HttpContext.Current.Trace.Write(Messages.successfulTransactionMessage);
            }
            catch (ImperialException ie)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = ie.ImperialMessage;
            }
            catch (Exception e)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = Messages.failureTransactionMessage;
                _logger.WriteEventViewerLog("LoadStatusesDropdownLists", e.Message, true);
            }
            finally
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.exitMessageInfo, "LoadStatusesDropdownLists"));
            }
        }

        /// <summary>
        /// Metodo que hace la carga de los ciudadanos existentes en la base de datos
        /// </summary>
        internal void LoadCurrentCitizens()
        {
            try
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.enterMessageInfo, "LoadCurrentCitizens"));
                DataTable dtCitizens = _controller.SelectAllCitizens();
                _view.SessionCurrentCitizens = dtCitizens;
                _view.CitizensDataSource = dtCitizens;
                HttpContext.Current.Trace.Write(Messages.successfulTransactionMessage);
            }
            catch (ImperialException ie)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = ie.ImperialMessage;
            }
            catch (Exception e)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = Messages.failureTransactionMessage;
                _logger.WriteEventViewerLog("LoadCurrentCitizens", e.Message, true);
            }
            finally
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.exitMessageInfo, "LoadCurrentCitizens"));
            }
        }

        /// <summary>
        /// Metodo que ejecuta la llamada al controlador para actualizar un ciudadano
        /// </summary>
        internal void UpdateCitizen()
        {
            CitizenEntity citizen = null;
            bool isAlreadyRegistered = false;
            try
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.enterMessageInfo, "UpdateCitizen"));
                if (_view.SessionCurrentCitizens == null)
                    _view.SessionCurrentCitizens = _controller.SelectAllCitizens();

                if (!_controller.IsTheSameCitizen(_view.UsernameText, _view.SessionCurrentCitizens, _view.SessionCurrentCitizen))
                    isAlreadyRegistered = _controller.CitizenAlreadyRegistered(_view.UsernameText, _view.SessionCurrentCitizens);

                if (!isAlreadyRegistered)
                {
                    citizen = _controller.CreateNewCitizen(_view.UsernameText, _view.RealnameText, _view.RoleValue, _view.RoleText, _view.SpecieValue, _view.SpecieText, _view.StatusValue, _view.StatusText);
                    citizen.Id = int.Parse(_view.SessionCurrentCitizen.ToString());

                    if (_controller.UserHasSkywalker(_view.RealnameText))
                    {
                        _view.SuccessfulTransaction = _controller.SendDataToWebService(citizen);
                        _view.TransactionMessage = _view.SuccessfulTransaction ? Messages.successfulTransactionMessage : Messages.failureTransactionMessage;
                    }
                    else if (_controller.UpdateCitizen(citizen))
                    {
                        _view.SuccessfulTransaction = true;
                        _view.TransactionMessage = Messages.successfulTransactionMessage;
                    }
                }
                else
                {
                    _view.SuccessfulTransaction = false;
                    _view.TransactionMessage = Messages.duplicatedCitizenMessage;
                }
                HttpContext.Current.Trace.Write(Messages.successfulTransactionMessage);
            }
            catch (ImperialException ie)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = ie.ImperialMessage;
            }
            catch (Exception e)
            {
                _view.SuccessfulTransaction = false;
                _view.TransactionMessage = Messages.failureTransactionMessage;
                _logger.WriteEventViewerLog("UpdateCitizen", e.Message, true);
            }
            finally
            {
                HttpContext.Current.Trace.Write(string.Format(Messages.exitMessageInfo, "UpdateCitizen"));
            }
        }

    }
}